package com.tongda.menu.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import com.tongda.core.common.Constants;
import com.tongda.core.common.KernalApplication;
import com.tongda.core.enums.StatusCodeEnum;
import com.tongda.core.repository.MenuCartDao;
import com.tongda.core.repository.MenuDishDao;
import com.tongda.core.service.TableService;
import com.tongda.core.service.UserService;
import com.tongda.core.utils.ActivityUtil;
import com.tongda.core.utils.SharedPreferencesUtils;
import com.tongda.core.vo.MobileRspResult;
import com.tongda.core.vo.Table;
import com.tongda.core.vo.TableArea;
import com.tongda.menu.R;
import com.tongda.menu.adapter.TableAreaAdapter;
import com.tongda.menu.adapter.TableGridAdapter;
import com.tongda.menu.widget.HorizontalListView;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class TableActivity extends BaseActivity {

	private GridView tableGv;
	private List<Table> tables;
	private TableGridAdapter tableAdapter;
	private String username;
	private String password;
	Map<String, Object> param = new WeakHashMap<String, Object>();
	public Button tableAllBtn;
	public Button tableFreeBtn;
	public Button tableUseBtn;
	
	public Button tableplaceAllBtn;
	public Button tableplaceHallBtn;
	public Button tableplaceRoomBtn;
	private HorizontalListView tablePlaceLv;
	private TableAreaAdapter tableAreaAdapter;
	private Spinner tableAreaSp;
	private boolean spBgFlag;
	private String currentArea ="全部";
	private String[] mItems;
	private ImageView refreshImv;
	
	private int currentPosition=0;
	private TableArea currentTableArea;
	private ImageView tableCloseImv;
	private TextView tablenumTv;
	private String order="no";
	private KernalApplication application;
	
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int what = msg.what;
			if(what==1){
				ActivityUtil.Toast(TableActivity.this, "清台成功", false, false);
			}else{
				ActivityUtil.Toast(TableActivity.this, Html.fromHtml("清台"+"<font color='red'>"+"失败"+"</font>")+"", false, false);
			}
			if(currentTableArea!=null){
				if(!currentTableArea.getName().equals("全部")){
					param.put("search_EQ_tableArea.areaId",currentTableArea.getAreaId());
				}
			}
			getTables();
		}
		
	};
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_table);
		tableGv = (GridView)findViewById(R.id.table_gridview);
		tablePlaceLv = (HorizontalListView)findViewById(R.id.tableplace_listView);
		tableAreaSp = (Spinner)findViewById(R.id.tablearea_sp);
		refreshImv = (ImageView)findViewById(R.id.table_refresh);
		tableCloseImv = (ImageView)findViewById(R.id.table_close);
		tablenumTv = (TextView)findViewById(R.id.table_numTv);
	    mItems = getResources().getStringArray(R.array.table_areas);
		// 建立Adapter并且绑定数据源
		ArrayAdapter<String> _Adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mItems);
		_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		//绑定 Adapter到控件
		tableAreaSp.setAdapter(_Adapter);
		
		application =  KernalApplication.getInstance();
		Intent intent = getIntent();
		order = intent.getStringExtra("order");
		new TableAreaTask().execute();
		
		tableCloseImv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
					TableActivity.this.finish();
					overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);
			}
		});
	}

	
	public class TableAreaTask extends AsyncTask<Void, Void, List<TableArea>>{
		private TableArea tableArea;
		private List<TableArea> tableAreas;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			tableArea = new TableArea();
			tableArea.setName("全部");
			
			tableAreas = new ArrayList<TableArea>();
			tableAreas.add(tableArea);
		}
		
		
		@Override
		protected List<TableArea> doInBackground(Void... params) {
			List<TableArea> result = TableService.getAllTableAreas();
			return result;
		}
		
		@Override
		protected void onPostExecute(List<TableArea> result) {
			super.onPostExecute(result);
			tableAreas.addAll(result);
			tableAreaAdapter = new TableAreaAdapter(tableAreas, TableActivity.this);
			tablePlaceLv.setAdapter(tableAreaAdapter);
			tableAreaAdapter.setCurrentPosition(currentPosition);
			
			tableAreaSp.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if(event.getAction()==MotionEvent.ACTION_DOWN){
						spBgFlag=!spBgFlag;
						if(spBgFlag){
							tableAreaSp.setBackgroundResource(R.drawable.spinner_up);
						}else{
							tableAreaSp.setBackgroundResource(R.drawable.spinner);
						}
					}
					return false;
				}
			});
			
			tableAreaSp.setOnItemSelectedListener(new OnItemSelectedListener() {
				
				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {
					    tableAreaSp.setBackgroundResource(R.drawable.spinner);
					    currentPosition = 0;
					    currentArea = mItems[position];
					    cancel(true);
						new TableAreaTask().execute();
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
						tableAreaSp.setBackgroundResource(R.drawable.spinner_up);
				}
				
			});
		
			refreshImv.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					currentPosition=0;
				    cancel(true);
					new TableAreaTask().execute();
				}
			});
			
			tablePlaceLv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					currentPosition = position;
					currentTableArea = tableAreas.get(position);
					if(!currentTableArea.getName().equals("全部")){
						param.put("search_EQ_tableArea.areaId",currentTableArea.getAreaId());
					}
						cancel(true);
						new TableAreaTask().execute();
				}
			});
			
			getTables();
	}
		
	}
	
	/**
	 * 获取当前选择餐台区域的餐台
	 * */
	@SuppressWarnings("unchecked")
	private void getTables(){
		if(currentArea.contains("全部")){
			
		}else if(currentArea.contains("空闲")){
			param.put("search_EQ_dinnerStatus",1);
		}else if(currentArea.contains("使用中")){
			param.put("search_EQ_dinnerStatus",2);
		}else if(currentArea.contains("已结账")){
			param.put("search_EQ_dinnerStatus",5);
		}
		param.put("search_EQ_restId", Constants.RESTAURANT_ID);
		new TablePlaceTask().execute(param);
	}
	
	public class TablePlaceTask extends AsyncTask<Map<String, Object>, Void, List<Table>>{

		@Override
		protected List<Table> doInBackground(Map<String, Object>... params) {
			tables = TableService.getRestTableList(params[0]);
			return tables;
		}
		
		@Override
		protected void onPostExecute(List<Table> result) {
			super.onPostExecute(result);
			tableAdapter = new TableGridAdapter(TableActivity.this, result);
			tableGv.setAdapter(tableAdapter);
			tableAdapter.notifyDataSetChanged();
			tableAdapter.notifyDataSetInvalidated();
			param.clear();
			
			tablenumTv.setText("当前共"+tableAdapter.getCount()+"个餐台");
		}
	}
	
	
	
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
		tableGv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				//2.2.0新的需求需要在这里加入身份的验证
				boolean isRem = (Boolean) SharedPreferencesUtils.getParam(TableActivity.this, Constants.MENU_IS_REM_CURRENTUSER, false);
				if(!isRem && !"yes".equals(order)){
					final AlertDialog dialog = new AlertDialog.Builder(TableActivity.this).create();
					View dialogView = View.inflate(TableActivity.this, R.layout.dialog_verifyid, null);
					dialog.setView(dialogView,0,0,0,0);
					dialog.show();
					final EditText ID_Edt = (EditText)dialogView.findViewById(R.id.verifyid_ID_edt);
				    final EditText PD_Edt = (EditText)dialogView.findViewById(R.id.verifyid_pw_edt);
					ImageView Cancel_Imv = (ImageView)dialogView.findViewById(R.id.verifyid_cancle);
					Button LG_Btn = (Button)dialogView.findViewById(R.id.verifyid_login_btn);
					final CheckBox isRemCb= (CheckBox)dialogView.findViewById(R.id.verifyid_remId);
					isRemCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						
						@Override
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							if(isRemCb.isChecked()){
								Toast.makeText(TableActivity.this, "记住登录状态,后续操作不用验证账号", Toast.LENGTH_SHORT).show();
							}else{
								Toast.makeText(TableActivity.this, "取消记住登录状态,后续操作验证账号", Toast.LENGTH_SHORT).show();
							}
						}
					});
					LG_Btn.setOnClickListener(new OnClickListener() {

						private int result;

						@Override
						public void onClick(View v) {
							 username = ID_Edt.getText().toString();
							 password = PD_Edt.getText().toString();
							 
								Thread loginThread = new Thread(new Runnable() {
									
									@Override
									public void run() {
										result = UserService.login(TableActivity.this, username, password, false);
									}
								});
								
								
							if(!username.equals("") && !password.equals("")){
								loginThread.start();
								try {
									loginThread.join();
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								
	                            if(result==0){
	                            	ActivityUtil.Toast(TableActivity.this, "身份验证成功", false, false);
									//把当前输入的账号密码记录到preference中
	                            	SharedPreferencesUtils.setParam(TableActivity.this, Constants.USERNAME, username);
									SharedPreferencesUtils.setParam(TableActivity.this, Constants.PASSWORD, password);
									SharedPreferencesUtils.setParam(TableActivity.this, Constants.MENU_IS_REM_CURRENTUSER, isRemCb.isChecked());
									dialog.dismiss();
									dealTable(position);
								}else{
									ActivityUtil.Toast(TableActivity.this, "身份验证失败", false, false);
								}
							}else{
								ActivityUtil.Toast(TableActivity.this, "用户名或密码为空", false, false);
							}
						}
					});
					Cancel_Imv.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							dialog.dismiss();
						}
					});
				}else{
					dealTable(position);
				}
			
		
	}

	public void dealTable(int position){
		final Table selectTable = tables.get(position);
		if(selectTable.getDinnerStatus().equals("1") || selectTable.getDinnerStatus().equals("2")){
			new openTableTask().execute(position);
		}else if(selectTable.getDinnerStatus().equals("5")){
			final AlertDialog dialog = new AlertDialog.Builder(TableActivity.this).create();
			View dialogView = View.inflate(TableActivity.this, R.layout.dialog_cleantable, null);
			dialog.setView(dialogView,0,0,0,0);
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();
			
			ImageView closeBtn = (ImageView)dialogView.findViewById(R.id.cleantable_close);
			TextView msgTv = (TextView)dialogView.findViewById(R.id.cleantable_msg);
			Button confirmBtn = (Button)dialogView.findViewById(R.id.cleantable_confirm);
			Button cancelBtn = (Button)dialogView.findViewById(R.id.cleantable_cancel);
			
			closeBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			msgTv.setText("餐台"+selectTable.getTabNo()+"确认清台？");
			confirmBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Thread clearTableThread = new Thread(new Runnable() {
						
						@Override
						public void run() {
							//当result等于true的时候表示该餐台清台成功
							MobileRspResult result = TableService.cleanTable(selectTable.getTabId());
							Message msg = handler.obtainMessage();
							msg.what=0;
							if(result.getStatusCode().equals(StatusCodeEnum.SUCCESS.getCode())){
								msg.what=1;
							}
							handler.sendMessage(msg);
						}
					});
					clearTableThread.start();
					dialog.dismiss();
				}
			});
			cancelBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
		}
		else{
			Toast("该餐桌不符合开台条件哦!");
		}
	}
});
	}
	public  void Toast(String taostStr){
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_layout,
		(ViewGroup) findViewById(R.id.toast_layout_root));

		ImageView image = (ImageView) layout.findViewById(R.id.image);
		image.setImageResource(R.drawable.toastimv);
		TextView text = (TextView) layout.findViewById(R.id.text);
		text.setGravity(Gravity.CENTER_VERTICAL);
		text.setText(taostStr);

		Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(layout);
		toast.show();
	}
	
	public class openTableTask extends AsyncTask<Integer, Void, Void>{
		private int position;
		private boolean hasPermission=false;
		@Override
		protected Void doInBackground(Integer... params) {
			position = params[0];
	    if(!UserService.getCurrentUserHasPermission("frontdesk_index_kaitai:create")){
	    	hasPermission = false;
		}else{
			hasPermission = true;
		}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if(!hasPermission){
				Toast("没有获取到您的开台权限!");
			}else{
				if(tables.get(position).getDinnerStatus().equals("1")){
					Table selectedTable = tables.get(position);
				    application.setMenuSelectedTable(selectedTable);
					TableActivity.this.finish();
					Intent intent = new Intent(TableActivity.this,OpenTableActivity.class);
					intent.putExtra("table", tables.get(position));
					intent.putExtra("dinnerStatus", tables.get(position).getDinnerStatus());
					intent.putExtra("order", order);
					startActivity(intent);
				}else if(tables.get(position).getDinnerStatus().equals("2")){
					Table selectedTable = tables.get(position);
					if(selectedTable==null || selectedTable.getBillId()==null || selectedTable.getBillId().equals("") || selectedTable.getTabNo()==null){
						Toast.makeText(TableActivity.this, "开台失败,请重新获取此餐台", Toast.LENGTH_SHORT).show();
					}else{
    				application.setMenuSelectedTable(selectedTable);
    				final MenuCartDao ordered_dish_dao = MenuCartDao.getInstance(TableActivity.this);
    				if(ordered_dish_dao.getAll("all").size()>0){
    			    Dialog dialog = new AlertDialog.Builder(TableActivity.this). 
    		                setTitle("警告！"). 
    		                setMessage("是否需要清空购物车中现有的菜肴"). 
    		                setPositiveButton("清空", new DialogInterface.OnClickListener() { 
    		                     
    		                    @Override 
    		                    public void onClick(DialogInterface dialog, int which) { 
    		            				
    		            				ordered_dish_dao.clearOrderDish();
    		            				
    		            				MenuDishDao dishdao = MenuDishDao.getInstance(TableActivity.this);
    		            				dishdao.cleardishorderNum();
   		            				    application.setBillNotes(null);
    		            				
    		            				dialog.dismiss();
    		            				TableActivity.this.finish();
    		            				application.setMenuMainIsRefresh(true);
    		            				
    		            				Intent intent = null;
    		            				intent  = new Intent(TableActivity.this,CartActivity.class);
    		            				intent.putExtra("order", order);
    		            				intent.putExtra("table", tables.get(position));
    		            				startActivity(intent);
    		            				overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);
    		                    } 
    		                }). 
    		                setNegativeButton("不清空", new DialogInterface.OnClickListener() {
    		                     
    		                    @Override 
    		                    public void onClick(DialogInterface dialog, int which) { 
    		            				
    		                    	dialog.dismiss();
    		                    	
    		                    	TableActivity.this.finish();
   	            				    application.setMenuMainIsRefresh(true);
    	            				
    	            				Intent intent = null;
    	            				intent  = new Intent(TableActivity.this,CartActivity.class);
    	            				intent.putExtra("order", order);
    	            				intent.putExtra("table", tables.get(position));
    	            				startActivity(intent);
    	            				overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);
    		                    } 
    		                }). 
    		                create(); 
    		        dialog.show();
					}else{
						TableActivity.this.finish();
						application.setMenuMainIsRefresh(true);
        				Intent intent = null;
    				    intent  = new Intent(TableActivity.this,CartActivity.class);
    					intent.putExtra("order", order);
    				    intent.putExtra("table", tables.get(position));
        				startActivity(intent);
        				overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);
					}
					}
				}
			}
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			TableActivity.this.finish();
			overridePendingTransition(R.anim.in_from_bottom, R.anim.out_to_top);
		}
		return super.onKeyDown(keyCode, event);
	}
}
